<?php

namespace App\Http\Controllers\Course;

use App\Events\Course;
use App\Http\Controllers\BaseController;
use App\Models\CourseChapter;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ChapterController extends BaseController
{
    public function index(Request $request)
    {
        $param = $this->validate($request,[
            'course_id' => 'required|integer'
        ]);

        $data = CourseChapter::query()
            ->where('course_id',$param['course_id'])
            ->orderBy('course_chapter_number_id')
            ->get();

        return $this->success($data);
    }


    public function study(Request $request)
    {
        $param = $this->validate($request,[
            'course_id' => 'required|integer',
        ]);

        $user_id = auth('api')->id();

        $browse_id =  DB::table('course_browses')
                        ->whereDate('view_time',date('Y-m-d'))
                        ->where('user_id',$user_id)
                        ->value('id');


        if (!$browse_id){
           $result =  DB::table('course_browses')
                ->insert([
                    'course_id' => $param['course_id'],
                    'user_id' => $user_id,
                    'view_count' => 1,
                    'view_time' => date('Y-m-d H:i:s')
                ]);
        }else{
            $result = DB::table('course_browses')->where('id',$browse_id)->increment('view_count');
        }

        event(new Course($user_id));

        return $result ? $this->success() : $this->error();
    }

    public function store(Request $request)
    {
        $param = $this->validate($request,[
            'course_chapter_number_id'=>'required|integer',
            'course_id' => 'required|integer',
            'name' => 'required',
            'video_url' => 'required',
            'video_poster' => 'required',
            'is_free' => 'required|in:0,1',
        ]);

        $param['user_id'] = auth('api')->id();
        $course = CourseChapter::query()->create($param);



        if ($course->getKey()){
            return $this->success();
        }

        return  $this->error();
    }


    public function update(Request $request)
    {
        $param = $this->validate($request,[
            'course_chapter_id' => 'required|integer',
            'course_chapter_number_id'=>'required|integer',
            'course_id' => 'required|integer',
            'name' => 'required',
            'video_url' => 'required',
            'video_poster' => 'required',
            'is_free' => 'required|in:0,1',
        ]);

        $course_chapter_id  = $param['course_chapter_id'];
        unset($param['course_chapter_id']);
        $result  = CourseChapter::query()->where('id',$course_chapter_id)->update($param);

        return $result ? $this->success() : $this->error();
    }
}
